<template>
  <div class="mainBox" v-if="isAdd">
    <div class="contentBox">
      <el-form :model="detailModel" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="品牌"
          :label-width="formLabelWidth"
          prop="bizPlatform"
        >
          <el-checkbox-group v-model="detailModel.bizPlatform">
            <el-checkbox
              v-for="item in bizPlatformOptions"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="端口"
          :label-width="formLabelWidth"
          prop="appPlatform"
        >
          <el-checkbox-group v-model="detailModel.appPlatform">
            <el-checkbox
              v-for="item in appPlatformOptions"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="客群"
          :label-width="formLabelWidth"
          prop="userType"
        >
          <el-radio-group v-model="detailModel.userType">
            <el-radio :label="2">展业员</el-radio>
            <el-radio :label="1">车主</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户"
          :label-width="formLabelWidth"
          prop="targetUid"
        >
          <el-radio-group v-model="detailModel.targetUid" @change="uidChange">
            <el-radio label="*">全部</el-radio>
            <el-radio label="1">指定群体</el-radio>
          </el-radio-group>
          <div class="txtBox">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 15 }"
              :formatter="(value) => value.replace(/[^\d|]/g, '')"
              v-model="targetUid"
              autocomplete="off"
              placeholder="用户ID，用多个'|'隔开"
              :disabled="isAllUid"
              style="width: 700px"
            />
            <el-upload
              :show-file-list="false"
              :auto-upload="false"
              accept=".txt"
              :on-change="openFile"
              :disabled="isAllUid"
            >
              <el-button link type="primary" size="small" :disabled="isAllUid"
                >上传</el-button
              >
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="主标题" :label-width="formLabelWidth" prop="title">
          <el-input
            v-model.trim="detailModel.title"
            maxlength="10"
            placeholder="字数请控制在10汉字以内"
            style="width: 700px"
          />
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
          <div style="border: 1px solid #dcdcdc">
            <!-- 工具栏 -->
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              style="border-bottom: 1px solid #ccc"
            />
            <!-- 编辑器 -->
            <Editor
              v-model="detailModel.content"
              :defaultConfig="addEditorConfig"
              style="height: 350px; width: 100%; font-size: 12px"
              @onCreated="handleCreated"
            />
          </div>
          <!-- <el-input
            v-model="detailModel.content"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 15 }"
            maxlength="50"
            placeholder="字数请控制在50汉字以内"
            style="width: 700px"
          /> -->
        </el-form-item>
        <el-form-item
          label="需要跳转"
          :label-width="formLabelWidth"
          prop="isJump"
        >
          <el-radio-group v-model="detailModel.isJump">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="detailModel.isJump === 1">
          <el-form-item label="跳转按钮" :label-width="formLabelWidth">
            <el-input
              v-model="detailModel.jumpInfoObj.button"
              maxlength="5"
              placeholder="字数请控制在5汉字以内"
            />
          </el-form-item>
          <el-form-item label="跳转方式" :label-width="formLabelWidth">
            <el-radio-group v-model="detailModel.jumpInfoObj.jumpType">
              <el-radio :label="0">端内</el-radio>
              <el-radio :label="1">H5页面</el-radio>
              <el-radio :label="2">微信小程序</el-radio>
              <el-radio :label="3">支付宝小程序</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="跳转地址" :label-width="formLabelWidth">
            <el-input
              v-model.trim="detailModel.jumpInfoObj.url"
              placeholder="请输入链接地址"
            />
          </el-form-item>
          <el-form-item
            label="H5跳转标题"
            :label-width="formLabelWidth"
            v-if="detailModel.jumpInfoObj.jumpType == 1"
          >
            <el-input
              v-model.trim="detailModel.jumpInfoObj.h5Title"
              placeholder="请输入H5跳转标题"
            />
          </el-form-item>
          <el-form-item
            label="APPID"
            :label-width="formLabelWidth"
            v-if="
              detailModel.jumpInfoObj.jumpType == 2 ||
              detailModel.jumpInfoObj.jumpType == 3
            "
          >
            <el-input
              v-model.trim="detailModel.jumpInfoObj.appId"
              placeholder="请输入APPID"
            />
          </el-form-item>
        </div>

        <el-form-item
          label="频率"
          :label-width="formLabelWidth"
          prop="frequency"
        >
          <el-radio-group v-model="detailModel.frequency">
            <el-radio :label="0">每天一次</el-radio>
            <el-radio :label="1">每打开一次</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="允许关闭"
          :label-width="formLabelWidth"
          prop="isClose"
        >
          <el-radio-group v-model="detailModel.isClose">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="生效时间"
          :label-width="formLabelWidth"
          prop="effectiveTime"
        >
          <el-date-picker
            v-model="detailModel.effectiveTime"
            type="datetime"
            placeholder="请选择生效时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item
          label="失效时间"
          :label-width="formLabelWidth"
          prop="expireTime"
        >
          <el-date-picker
            v-model="detailModel.expireTime"
            type="datetime"
            placeholder="请选择失效时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <div class="subBtnBox">
        <el-button
          type="primary"
          color="#ea5b24"
          @click="formSubmit(ruleFormRef)"
          >保存</el-button
        >
        <el-button
          type="primary"
          color="#ea5b24"
          @click="emit('packConfigBack')"
          >返回</el-button
        >
      </div>
    </div>
  </div>
  <div class="mainBox" v-else>
    <div class="descriptionsBox">
      <el-descriptions :column="1" border>
        <el-descriptions-item
          label="品牌"
          label-align="right"
          label-class-name="labelCss"
        >
          {{ detailModel.bizPlatform }}
        </el-descriptions-item>
        <el-descriptions-item label="端口" label-align="right">
          {{ detailModel.appPlatform }}
        </el-descriptions-item>
        <el-descriptions-item label="客群" label-align="right">
          {{ detailModel.userType }}
        </el-descriptions-item>
        <el-descriptions-item label="用户" label-align="right">
          {{ detailModel.targetUid }}
          <div class="txtBox">
            {{ targetUid }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="主标题" label-align="right">
          {{ detailModel.title }}
        </el-descriptions-item>
        <el-descriptions-item label="内容" label-align="right">
          <div class="txtBox">
            <Editor
              v-model="detailModel.content"
              :defaultConfig="showInfoEditorConfig"
              style="width: 100%; overflow-y: hidden"
              @onCreated="handleCreated"
            />
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="需要跳转" label-align="right">
          {{ detailModel.isJump == 1 ? "是" : "否" }}
        </el-descriptions-item>
        <div v-if="detailModel.isJump == 1">
          <el-descriptions-item label="跳转按钮" label-align="right">
            {{ detailModel.jumpInfoObj.button }}
          </el-descriptions-item>
          <el-descriptions-item label="跳转方式" label-align="right">
            {{ judgeJumpType(detailModel.jumpInfoObj.jumpType) }}
          </el-descriptions-item>
          <el-descriptions-item label="跳转地址" label-align="right">
            <div class="txtBox">
              {{ detailModel.jumpInfoObj.url }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item
            label="H5跳转标题"
            label-align="right"
            v-if="detailModel.jumpInfoObj.jumpType == 1"
          >
            {{ detailModel.jumpInfoObj.h5Title }}
          </el-descriptions-item>
          <el-descriptions-item
            label="APPID"
            label-align="right"
            v-if="
              detailModel.jumpInfoObj.jumpType == 2 ||
              detailModel.jumpInfoObj.jumpType == 3
            "
          >
            {{ detailModel.jumpInfoObj.appId }}
          </el-descriptions-item>
        </div>
        <el-descriptions-item label="频率" label-align="right">
          {{ detailModel.frequency == 1 ? "每打开1次" : "每天1次" }}
        </el-descriptions-item>
        <el-descriptions-item label="允许关闭" label-align="right">
          {{ detailModel.isClose == 1 ? "允许" : "不允许" }}
        </el-descriptions-item>
        <el-descriptions-item label="生效时间" label-align="right">
          {{ detailModel.effectiveTime }}
        </el-descriptions-item>
        <el-descriptions-item label="失效时间" label-align="right">
          {{ detailModel.expireTime }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="subBtnBox">
        <div v-if="noticeState == 0" style="margin-right: 15px">
          <el-button
            type="primary"
            color="#ea5b24"
            @click="toExamine(1)"
            v-if="pinia.isShow[146]"
            >审核通过</el-button
          >
          <el-button
            type="primary"
            color="#ea5b24"
            @click="isShowDialogVisible = true"
            v-if="pinia.isShow[147]"
            >审核不通过</el-button
          >
        </div>
        <el-button
          type="primary"
          color="#ea5b24"
          @click="emit('packConfigBack')"
          >返回</el-button
        >

        <el-dialog
          v-model="isShowDialogVisible"
          title="公告审核"
          center="true"
          modal="true"
          width="450px"
        >
          <el-form :model="toExamineModel">
            <el-form-item label="不通过原因">
              <el-input
                v-model="toExamineModel.checkNote"
                :autosize="{ minRows: 4 }"
                placeholder="请输入不通过原因."
                type="textarea"
                autocomplete="off"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="isShowDialogVisible = false">取消</el-button>
              <el-button type="primary" color="#ea5b24" @click="toExamine(2)"
                >确定</el-button
              >
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  findNoticeInfoByIdApi,
  addNoticeApi,
  checkNoticeApi,
} from "../../../api/index";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { usePermissStore } from "../../../store/permiss";
// 富文本
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const pinia = usePermissStore();

// 富文本编辑器实例
const editorRef = shallowRef();
// 工具栏配置
let toolbarConfig = {
  /* 工具栏配置 */
  toolbarKeys: [
    "headerSelect",
    // "blockquote",
    "bold",
    "underline",
    "italic",
    {
      key: "group-more-style", // 必填，要以 group 开头
      title: "更多", // 必填
      menuKeys: ["through", "code", "sup", "sub", "clearStyle"], // 下级菜单 key ，必填
    },
    "|",
    "color",
    "bgColor",
    "|",
    "fontSize",
    "fontFamily",
    "lineHeight",
    "|",
    "bulletedList",
    "numberedList",
    // "todo",
    {
      key: "group-justify",
      title: "对齐",
      menuKeys: [
        "justifyLeft",
        "justifyRight",
        "justifyCenter",
        "justifyJustify",
      ],
    },
    // {
    //   key: "group-indent",
    //   title: "缩进",
    //   menuKeys: ["indent", "delIndent"],
    // },
    // "|",
    // "emotion",
    // "insertLink",
    // "insertTable",
    // "codeBlock",
    // "divider",
    // "|",
    // "undo",
    // "redo",
  ],
};

// 新增公告时编辑器配置
const addEditorConfig = {
  placeholder: "字数请控制在50汉字以内",
  maxLength: 50,
  MENU_CONF: {
    // color: {
    //   colors: ["red"],
    // },
  },
};
// 展示详情时编辑器配置
const showInfoEditorConfig = {
  readOnly: true,
};

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 父级传递过来的参数
const props = defineProps({
  detaildData: Object,
});
//父级传递的方法
const emit = defineEmits(["packConfigBack"]);
const formLabelWidth = "200px";

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  bizPlatform: [{ required: true, message: "请选择品牌", trigger: "blur" }],
  appPlatform: [{ required: true, message: "请选择端口", trigger: "blur" }],
  userType: [{ required: true, message: "请选择客群", trigger: "blur" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  // content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  isJump: [{ required: true, message: "请选择是否需要跳转", trigger: "blur" }],
  frequency: [{ required: true, message: "请选择频率", trigger: "blur" }],
  isClose: [{ required: true, message: "请选择是否允许关闭", trigger: "blur" }],
  effectiveTime: [
    { required: true, message: "请选择生效时间", trigger: "blur" },
  ],
  expireTime: [{ required: true, message: "请选择失效时间", trigger: "blur" }],
});

// 判断是新增还是审核
let isAdd: any = ref(true);
let noticeID = null;
// 跑马灯状态
let noticeState: any = ref(null);

// 控制不通过原因输入框
let isShowDialogVisible = ref(false);

// 用户控制
let isAllUid = ref(true);
let targetUid = ref(null);

// 广告详情数据模型
let detailModel: any = reactive({
  bizPlatform: [],
  appPlatform: ["android", "ios"],
  userType: null,
  targetUid: "*",
  title: null,
  content: null,
  isJump: null,
  jumpInfoObj: {
    button: null,
    jumpType: null,
    url: null,
    appId: null,
    h5Title: null,
  },
  frequency: null,
  isClose: null,
  effectiveTime: null,
  expireTime: null,
});

// 审核参数模型
let toExamineModel: any = reactive({
  id: null,
  state: null,
  checkNote: null,
});

// 品牌枚举
const bizPlatformOptions: any = reactive([
  { value: "ybt", label: "壹佰通" },
  { value: "cxw", label: "车讯网" },
  { value: "wnsj", label: "华行通" },
  { value: "kyx", label: "阔悦行" },
]);

// 端口枚举
const appPlatformOptions: any = reactive([
  { value: "wx", label: "微信小程序" },
  { value: "alipay", label: "支付宝小程序" },
  { value: "android", label: "android客户端" },
  { value: "ios", label: "IOS客户端" },
]);

const uidChange = (val) => {
  switch (val) {
    case "*":
      isAllUid.value = true;
      targetUid.value = "";
      break;
    case "1":
      isAllUid.value = false;
      break;
  }
};

// 过滤跳转方式
const judgeJumpType = (val) => {
  switch (val) {
    case 0:
      return "端内页面";
    case 1:
      return "H5页面";
    case 2:
      return "微信小程序";
    case 3:
      return "支付宝小程序";
    default:
      return "";
  }
};

//上传txt文档
const openFile = (file) => {
  if (!file) {
    // 没有文件
    return false;
  } else if (!/\.(txt)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    ElMessage.error("上传格式不正确，请上传txt格式.");
    return false;
  }
  var reader = new FileReader();
  reader.onload = function () {
    if (reader.result) {
      //打印文件内容
      targetUid.value = reader.result;
    }
  };
  reader.readAsText(file.raw);
};

// 查询账单详情信息
const findNoticeInfo = (id) => {
  findNoticeInfoByIdApi(id).then((res) => {
    if (res.data.code === 2000) {
      noticeState.value = res.data.data.state;
      detailModel.appPlatform = res.data.data.appPlatform.replaceAll("|", ",");
      detailModel.bizPlatform = res.data.data.bizPlatform.replaceAll("|", ",");
      if (res.data.data.userType == 1) {
        detailModel.userType = "车主";
      } else {
        detailModel.userType = "代理员";
      }
      if (res.data.data.targetUid == "*") {
        detailModel.targetUid = "全部用户";
      } else {
        detailModel.targetUid = "指定群体";
        targetUid.value = res.data.data.targetUid;
      }
      detailModel.title = res.data.data.title;
      detailModel.content = res.data.data.content;
      detailModel.isJump = res.data.data.isJump;
      if (res.data.data.jumpInfoObj) {
        detailModel.jumpInfoObj.button = res.data.data.jumpInfoObj.button;
        detailModel.jumpInfoObj.jumpType = res.data.data.jumpInfoObj.jumpType;
        detailModel.jumpInfoObj.url = res.data.data.jumpInfoObj.url;
        detailModel.jumpInfoObj.h5Title = res.data.data.jumpInfoObj.h5Title;
        detailModel.jumpInfoObj.appId = res.data.data.jumpInfoObj.appId;
        // detailModel.jumpInfoObj.alipayInfo = res.data.data.jumpInfoObj.alipayInfo;
      }
      detailModel.frequency = res.data.data.frequency;
      detailModel.isClose = res.data.data.isClose;
      detailModel.effectiveTime = res.data.data.effectiveTime;
      detailModel.expireTime = res.data.data.expireTime;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 添加提交
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (detailModel.content == "<p><br></p>") {
        ElMessage.warning("请输入内容.");
        return;
      }
      if (detailModel.content.replace(/<[^>]+>/g, "").length > 50) {
        ElMessage.warning("字数请控制在50字以内.");
        return;
      }
      if (detailModel.isJump == 1) {
        if (!detailModel.jumpInfoObj.button) {
          ElMessage.warning("请填写跳转按钮.");
          return;
        }
        if (detailModel.jumpInfoObj.jumpType == null) {
          ElMessage.warning("请选择跳转方式.");
          return;
        }
        if (!detailModel.jumpInfoObj.url) {
          ElMessage.warning("请输入跳转地址.");
          return;
        }
        if (
          detailModel.jumpInfoObj.jumpType == 1 &&
          !detailModel.jumpInfoObj.h5Title
        ) {
          ElMessage.warning("请输入H5跳转标题.");
          return;
        }
        if (
          (detailModel.jumpInfoObj.jumpType == 2 ||
            detailModel.jumpInfoObj.jumpType == 3) &&
          !detailModel.jumpInfoObj.appId
        ) {
          ElMessage.warning("请输入APPID.");
          return;
        }
      }
      if (detailModel.targetUid != "*") {
        if (targetUid.value) {
          detailModel.targetUid = targetUid.value;
        } else {
          ElMessage.warning("请输入用户ID.");
          return;
        }
      }
      if (detailModel.bizPlatform) {
        detailModel.bizPlatform = detailModel.bizPlatform.join("|");
      }
      if (detailModel.bizPlatform) {
        detailModel.appPlatform = detailModel.appPlatform.join("|");
      }
      addNoticeApi(detailModel).then((res) => {
        if (res.data.code === 2000) {
          ElMessage({
            message: "添加成功.",
            type: "success",
          });
          noticeID = res.data.data;
          findNoticeInfo(noticeID);
          isAdd.value = false;
        } else {
          detailModel.bizPlatform = detailModel.bizPlatform.split("|");
          detailModel.appPlatform = detailModel.appPlatform.split("|");
          switch (res.data.code) {
            case 4001:
              ElMessage.error("指定用户文本格式不合法.");
              break;
            case 4002:
              ElMessage.error("生效时间必须在失效时间之前.");
              break;
            case 4003:
              ElMessage.error("生效时间段有重叠，添加失败.");
              break;
            default:
              ElMessage.error("添加失败.");
              break;
          }
        }
      });
    } else {
      return false;
    }
  });
};

// 审核
const toExamine = (state) => {
  if (
    state == 2 &&
    (toExamineModel.checkNote == "" || toExamineModel.checkNote == null)
  ) {
    ElMessage.error("请输入不通过原因.");
    return;
  }
  toExamineModel.state = state;
  toExamineModel.id = noticeID;
  checkNoticeApi(toExamineModel).then((res) => {
    if (res.data.code === 2000) {
      ElMessage({
        message: "审核成功.",
        type: "success",
      });
      isShowDialogVisible.value = false;
      emit("packConfigBack");
    } else {
      ElMessage.error("审核失败.");
    }
  });
};

onMounted(() => {
  if (props.detaildData.id) {
    noticeID = props.detaildData.id;
    isAdd.value = false;
    findNoticeInfo(noticeID);
  } else {
    isAdd.value = true;
    // 获取当前时间
    let nowTime = new Date().getTime();
    detailModel.effectiveTime = pinia.timeConversion(nowTime);
  }
});
</script>

<style scoped>
.mainBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 40px;
  /* border: 1px solid red; */
  width: 100%;
}
.contentBox {
  background-color: #ffffff;
  border-radius: 32px;
  box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 900px;
  display: flex;
  flex-direction: column;
}

.descriptionsBox {
  /* border: 1px solid red; */
  width: 900px;
  padding-bottom: 40px;
  display: flex;
  flex-direction: column;
}

.previewImgBox {
  border: 1px solid #99a2b2;
  max-width: 100px;
}

.previewImg {
  width: 100%;
  height: 100%;
}

.subBtnBox {
  width: 100%;
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

:deep(.labelCss) {
  width: 100px;
}

.txtBox {
  display: flex;
  word-break: break-all;
  width: 100%;
}

:deep(.w-e-scroll) {
  color: #666666;
}
</style>
